package com.oglvip.business.extend.advice;

import com.oglvip.business.consts.common.ResponseCode;
import com.oglvip.business.dto.ResponseData;
import com.oglvip.business.extend.exception.ArgsValidException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;

import javax.servlet.http.HttpServletRequest;

/**
 * @auther hanchao
 * @date 2016/12/10 17:19
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    private static final Logger _logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {BindException.class, ArgsValidException.class})
    @ResponseBody
    public ResponseData paramErrorHandler(HttpServletRequest request, Exception exception) {
        log.error(ExceptionUtils.getStackTrace(exception));

        ResponseData result = ResponseData.builder().build().setResponseCode(ResponseCode.WRONG_PARAM);
        return result;
    }

    @ExceptionHandler(HttpClientErrorException.class)
    @ResponseBody
    public ResponseData serviceErrorHandler(HttpServletRequest request,Exception exception){
        log.error(ExceptionUtils.getStackTrace(exception));

        if(exception instanceof HttpClientErrorException){
            log.error(((HttpClientErrorException) exception).getResponseBodyAsString());
        }
        ResponseData result = ResponseData.builder().build().setResponseCode(ResponseCode.SERVER_ERROR);
        return result;
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseData globalErrorHandler(HttpServletRequest request,Exception exception){
        log.error(ExceptionUtils.getStackTrace(exception));
        ResponseData result = ResponseData.builder().build().setResponseCode(ResponseCode.SERVER_ERROR);
        return result;
    }
}
